﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using WoltersKluwer.SPChainGang.Core.Constants;
using WoltersKluwer.SPChainGang.Core.Data.Entity;
using WoltersKluwer.SPChainGang.Core.Util;

namespace WoltersKluwer.SPChainGang.Core.ObjectScanners
{
    class SitePagesScanner : ScannerBase
    {
        public SitePagesScanner(
            SPSite targetSiteCollection, Guid configurationListId, JobMode mode, Guid jobId, string reportFolder,
            List<ConfigurationMapping> mappings)
            : base(targetSiteCollection, configurationListId, mode, jobId, reportFolder, mappings)
        {
        }

        public override void Scan(SPWeb web)
        {
            ScanFilesRecursive(web.RootFolder, web.Url);
        }

        void ScanFilesRecursive(SPFolder folder, string webUrl)
        {
#if SOS
            Logger.Log(JobId, "SitePagesScanner ScanFilesRecursive() folder={0} weburl={1}", folder.Url, webUrl);
#endif
            var files = folder.Files;
            int filesCount = files.Count;
#if SOS
            Logger.Log(JobId, "SitePagesScanner ScanFilesRecursive() folder.Files.Count={0}", folder.Files.Count.ToString());
#endif
            for (int i = 0; i < filesCount; i++)
            {
                SPFile file = files[i];
                if (file == null || (file.InDocumentLibrary && (file.Item !=null) && IsPublishingPages(file.Item.ParentList)) || !IsContentFile(file.Name)) continue;

                Uri fileLocation = LinkHelpers.MakeUri(webUrl, file.ServerRelativeUrl);
#if SOS
                Logger.Log(JobId, "SitePagesScanner ScanFilesRecursive() fileLocation={0} file={1}", fileLocation.ToString(), file.ServerRelativeUrl );
#endif
                ScanFileContents(file, fileLocation);
                if (IsAspxFile(file.Name))
                {
#if SOS
                    Logger.Log(JobId, "SitePagesScanner file={0} is aspx", file.ServerRelativeUrl);
#endif
                    ScanWebParts(file, fileLocation);
                }
            }

            foreach (SPFolder subFolder in folder.SubFolders)
            {
                try
                {
                    ScanFilesRecursive(subFolder, webUrl);
                }
                catch (Exception ex)
                {
                    Logger.LogError(JobId, "Scan subfolder failed", ex);
                }
            }
        }

       
    }
}
